/*
 * @(#)Server.java	Robert Denda & Christoph Kuhmünch
 */

/** 
 *
 * @author 	Robert Denda
 * @version     1.0, 20.06.97
 * @see Client
 * @see Connection
 * @see SimulationServer
 *
 */

import java.net.*;
import java.util.*;
import java.io.*;

public class Server implements Runnable {

  ServerControlWindow scw;
  Vector              connections;
  
  
  ServerSocket        listener;
  Thread              serverThread;
  debug DEBUG;

  public Server( int portNumber ) {
    DEBUG = new debug();
    connections = new Vector();
    try {
      listener = new ServerSocket( portNumber );
    } catch( IOException e ) {
      System.out.println("fatal ServerSocket Exception!");
      System.out.println(e);
      System.exit(-1);
    } // try

    scw= new ServerControlWindow(this);
    scw.pack();
    scw.show();

    serverThread = new Thread( this );
    serverThread.start();
  } // Server.Server

  synchronized public void run() {
    try {
      for ( ;; ) {
	Socket client = listener.accept(); // wait for connection
	InputStream input = client.getInputStream();
	Connection connection = new Connection( client );
	connections.addElement( connection );
        scw.addClient(connection.getRemoteName());
      } // for
    } catch( IOException e ) {
      System.out.println("Exception while accept:");
      System.out.println(e);
    } // try
  } // Server.run

  public void sendEvent( String eventName ) {
    if ( connections != null ) {
      scw.sndActive();
      Vector deadConnections= new Vector();
      for ( int i = 0; i < connections.size(); i += 1 ) {
        Connection c= ( Connection ) connections.elementAt( i );
        try {
          c.write( eventName );
        }
        catch( IOException e) {
          deadConnections.addElement(c);
        }        
      } // for
      
      for ( int i = 0; i < deadConnections.size(); i += 1 ) {
        Connection c= (Connection) deadConnections.elementAt(i);
        scw.removeClient(c.getRemoteName());
        connections.removeElement(c);
        System.out.println("remove client");
      }

      scw.sndInactive();
    } // if
  } // Server.sendEvent

} // Server

